package jdktcp.server;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class JDKServer05BrokenPipe {

    static ExecutorService pool = Executors.newFixedThreadPool(100);

    public JDKServer05BrokenPipe() throws Exception {
        ServerSocket server = new ServerSocket(9999);
        System.out.println("init server :" + server);
        while (true) {
            Socket socket = server.accept();
            System.out.println("--->" + socket);
            execute(socket);
        }
    }

    private void execute(Socket socket) {
        pool.submit(() -> {
            try {
                byte[] buff = new byte[1024];
                InputStream in = socket.getInputStream();
                in.read(buff);
                System.out.println("revice==>" + new String(buff).trim());

                //必须先等待一会?
                TimeUnit.SECONDS.sleep(10);
                OutputStream out = socket.getOutputStream();

                out.write("nihao".getBytes());
                System.out.println("send one finish <---");

                //FIX1 连续发送时如果第2次写之前,client关闭了socket会出现broken pipe
                TimeUnit.MILLISECONDS.sleep(10);
                out.write("nihao-2".getBytes());//此行write出现异常
                System.out.println("send two finish <---");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(socket);
            }
        });
    }

    public static void main(String[] args) throws Exception {
        new JDKServer05BrokenPipe();
    }
}
